<template>
    <div class="app-container">
      <!-- 推送消息模块 -->
      <section class="message-push">
        <h3>模拟推送消息：</h3>
        <div class="input-group">
          <textarea 
            v-model="pushContent"
            placeholder="输入要推送的消息内容"
            class="message-input"
          ></textarea>
          <button 
            @click="pushMsg"
            :disabled="!isConnected"
            class="send-button"
          >
            {{ isConnected ? '发布通告' : '连接中...' }}
          </button>
        </div>
      </section>
  
      <!-- 消息接收模块 -->
      <section class="message-receive">
        <h3>最新消息：<span class="latest-message">{{ message }}</span></h3>
        <div class="message-history">
          <h4>历史消息记录：</h4>
          <div v-if="msgs.length === 0" class="empty-tip">暂无消息</div>
          <ul v-else class="message-list">
            <li 
              v-for="(msg, index) in msgs"
              :key="index"
              class="message-item"
            >
              {{ msg }}
            </li>
          </ul>
        </div>
      </section>
  
      <!-- 实时数据模块 -->
      <section class="real-time-data">
        <h3>设备实时状态：</h3>
        <div class="status-container">
          <div class="status-item">
            <span class="status-label">状态1：</span>
            <span 
              class="status-value"
              :class="{ 'active': dataInfo.status1 === 'on' }"
            >
              {{ dataInfo.status1 }}
            </span>
          </div>
          <div class="status-item">
            <span class="status-label">状态2：</span>
            <span 
              class="status-value"
              :class="{ 'active': dataInfo.status2 === 'on' }"
            >
              {{ dataInfo.status2 }}
            </span>
          </div>
        </div>
      </section>
  
      <!-- 连接状态提示 -->
      <div v-if="connectionError" class="error-alert">
        连接错误: {{ connectionError }}
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { HubConnectionBuilder } from '@microsoft/signalr';
  
  // 配置常量
  const API_BASE_URL = 'http://localhost:3000';
  const CHAT_HUB_URL = `${API_BASE_URL}/chatHub`;
  const PUSH_MSG_URL = `${API_BASE_URL}/A_UpperComputer/PushMsg`;
  
  export default {
    name: 'SignalRClient',
    data() {
      return {
        message: "等待接收消息...",
        msgs: [],
        dataInfo: {
          status1: "off",
          status2: "off"
        },
        pushContent: "",
        connection: null,
        isConnected: false,
        connectionError: null,
        reconnectAttempts: 0,
        signalRUrl: CHAT_HUB_URL,
        maxReconnectAttempts: 5
      };
    },
  

    created() {
     
   
      this.initSignalRConnection();
    },
    beforeDestroy() {
      this.cleanupConnection();
    },
    methods: {
      // 初始化 SignalR 连接
      async initSignalRConnection() {
        try {
   
        //  this.signalRUrl="http://192.168.110.183:8088/chatHub";
          console.log(this.signalRUrl);
          this.connection = new HubConnectionBuilder()
            .withUrl(this.signalRUrl)
            .withAutomaticReconnect()
            .build();
  
          // 注册事件处理器
          this.connection.on("showmsg", this.handleShowMessage);
          this.connection.on("updatedata", this.handleUpdateData);
          
          // 监听连接状态变化
          this.connection.onreconnecting(() => {
            this.isConnected = false;
            console.warn('Connection lost, attempting to reconnect...');
          });
  
          this.connection.onreconnected(() => {
            this.isConnected = true;
            console.info('Connection reestablished');
          });
  
          // 启动连接
          await this.connection.start();
          this.isConnected = true;
          this.connectionError = null;
          console.info('SignalR 连接成功');
  
        } catch (error) {
          this.handleConnectionError(error);
        }
      },
  
      // 清理连接
      cleanupConnection() {
        if (this.connection) {
          this.connection.off("showmsg");
          this.connection.off("updatedata");
          this.connection.stop();
        }
      },
  
      // 处理消息显示
      handleShowMessage(msgInfo) {
        //const formattedMsg = `${new Date().toLocaleTimeString()} - ${msgInfo.title}: ${msgInfo.msgContent}`;
        const formattedMsg = `${new Date().toLocaleTimeString()}  ${msgInfo.msgContent}`;
        this.message = formattedMsg;
        this.msgs = [...this.msgs.slice(-9), formattedMsg]; // 保留最近10条消息
      },
  
      // 处理数据更新
      handleUpdateData(dataMsg) {
        this.dataInfo = { 
          ...this.dataInfo,
          ...dataMsg 
        };
      },
  
      // 发送消息
      async pushMsg() {
        if (!this.pushContent.trim()) {
          alert('消息内容不能为空');
          return;
        }
  
        try {
          const response = await axios.get(PUSH_MSG_URL, {
            params: { content: this.pushContent }
          });
          
          if (response.data.success) {
            this.pushContent = "";
            console.log('消息推送成功');
          }
        } catch (error) {
          console.error('消息推送失败:', error);
          alert('消息推送失败，请检查网络连接');
        }
      },
  
      // 处理连接错误
      handleConnectionError(error) {
        this.connectionError = error.message;
        this.isConnected = false;
        console.error('SignalR 连接失败:', error);
        
        // 自动重连逻辑
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
          setTimeout(() => {
            this.reconnectAttempts++;
            console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            this.initSignalRConnection();
          }, 5000);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .app-container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
    font-family: Arial, sans-serif;
  }
  
  /* 通用样式 */
  h3 {
    color: #333;
    border-bottom: 2px solid #eee;
    padding-bottom: 0.5rem;
  }
  
  .input-group {
    margin: 1rem 0;
  }
  
  /* 消息输入框 */
  .message-input {
    width: 100%;
    height: 100px;
    padding: 0.8rem;
    border: 2px solid #ddd;
    border-radius: 4px;
    resize: vertical;
    transition: border-color 0.3s;
  }
  
  .message-input:focus {
    border-color: #409eff;
    outline: none;
  }
  
  /* 按钮样式 */
  .send-button {
    background: #409eff;
    color: white;
    border: none;
    padding: 0.8rem 1.5rem;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
  }
  
  .send-button:disabled {
    background: #a0cfff;
    cursor: not-allowed;
  }
  
  .send-button:hover:not(:disabled) {
    background: #79bbff;
  }
  
  /* 消息列表 */
  .message-list {
    list-style: none;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #eee;
    border-radius: 4px;
  }
  
  .message-item {
    padding: 0.8rem;
    border-bottom: 1px solid #eee;
  }
  
  .message-item:last-child {
    border-bottom: none;
  }
  
  /* 状态显示 */
  .status-container {
    display: grid;
    gap: 1rem;
    padding: 1rem;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .status-item {
    display: flex;
    align-items: center;
    gap: 1rem;
  }
  
  .status-label {
    font-weight: bold;
    min-width: 60px;
  }
  
  .status-value {
    padding: 0.3rem 0.8rem;
    border-radius: 12px;
    background: #f0f0f0;
  }
  
  .status-value.active {
    background: #67c23a;
    color: white;
  }
  
  /* 错误提示 */
  .error-alert {
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 1rem;
    background: #f56c6c;
    color: white;
    border-radius: 4px;
    animation: slideIn 0.3s;
  }
  
  @keyframes slideIn {
    from { transform: translateX(100%); }
    to { transform: translateX(0); }
  }
  
  .empty-tip {
    color: #909399;
    text-align: center;
    padding: 1rem;
  }
  </style>
  